import React, { Component, Fragment } from "react";
import TodoItem from "./TodoItem";

class TodoList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inputValue: "Monday!",
      list: [],
    };
    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleBtnClick = this.handleBtnClick(this)
    this.handleItemDelete = this.handleItemDelete.bind(this)

  }

  render() {
    return (
      <Fragment>
        <div>
          <label htmlFor="insertArea">输入内容</label>
          <input
            id="insertArea"
            className="input"
            value={this.state.inputValue}
            onChange={this.handleInputChange}
          />
          <button onClick={this.handleBtnClick}>提交</button>
        </div>
        <ul>
          {this.state.list.map((item, index) => {
            return(
                <TodoItem
                    key={index}
                    content={item}
                    index={index}
                    deleteItem={this.handleItemDelete}
                 />
                /*
            <li key={index}
                onClick={this.handleItemDelete.bind(this, index)}
                dangerouslySetInnerHTML={{__html:item}}
                >

            </li>)
            */
            )
          })}
        </ul>
      </Fragment>
    );
  }

  handleItemDelete(index){
    const list = [...this.state.list];
    list.splice(index,1);
    this.setState({
        list:list
    })
  }

  handleBtnClick() {
    this.setState((prestate)=>({
      list: [...prestate.list,prestate.inputValue],
      inputValue: "",
    }));
  }

  handleInputChange(e) {
    const value = e.target.value
    this.setState({
      inputValue: value,
    });
  }
}
export default TodoList;
